package com.ypj.community.service;

import com.ypj.community.dao.elasticsearch.DiscussPostRepository;
import com.ypj.community.domain.DiscussPost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ElasticsearchService {

    @Autowired
    private DiscussPostRepository discussPostRepository;
    @Autowired
    private ElasticsearchRestTemplate restTemplate;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public void saveDiscussPost(DiscussPost discussPost){
         discussPostRepository.save(discussPost);
    }
    public void deleteDiscussPost(int id){
        discussPostRepository.deleteById(id);
    }
    public Page<DiscussPost> searchDiscussPost(String keyword,int current,int limit) throws IOException{
        SearchRequest searchRequest=new SearchRequest("discusspost");
        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.field("content");
        highlightBuilder.requireFieldMatch(false);
        highlightBuilder.preTags("<em>");
        highlightBuilder.postTags("</em>");

        SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder().query(QueryBuilders.multiMatchQuery(keyword,"title","content"))
                .sort(SortBuilders.fieldSort("type").order(SortOrder.DESC))
                .sort(SortBuilders.fieldSort("score").order(SortOrder.DESC))
                .sort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
                .from(current)//查询起始位置
                .size(limit).highlighter(highlightBuilder);
//                .highlighter(new HighlightBuilder().field("title").preTags("<em>").postTags("</em>"))//高亮显示不能这样写会被后面的覆盖
//                .highlighter(new HighlightBuilder().field("content").preTags("<em>").postTags("</em>"));
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse=restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits=searchResponse.getHits();
        if (hits.getHits().length<=0){
            return null;
        }
        List<DiscussPost> list=new ArrayList<>();
        for (SearchHit hit:hits.getHits()){
            DiscussPost discussPost=new DiscussPost();
            String id=hit.getSourceAsMap().get("id").toString();
            discussPost.setId(Integer.valueOf(id));

            String userId=hit.getSourceAsMap().get("userId").toString();
            discussPost.setUserId(Integer.valueOf(userId));

            String title=hit.getSourceAsMap().get("title").toString();
            discussPost.setTitle(title);

            String content=hit.getSourceAsMap().get("content").toString();
            discussPost.setContent(content);

            String status=hit.getSourceAsMap().get("status").toString();
            discussPost.setStatus(Integer.valueOf(status));

            String createTime=hit.getSourceAsMap().get("createTime").toString();
            //System.out.println(createTime );
            createTime=createTime.replace("Z"," UTC");
            //System.out.println(createTime);
            Date date=null;
            try {
                date=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z").parse(createTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //System.out.println(date);
            discussPost.setCreateTime(date);
            //discussPost.setCreateTime(new Date(Long.valueOf(createTime)));

            String commentCount=hit.getSourceAsMap().get("commentCount").toString();
            discussPost.setCommentCount(Integer.valueOf(commentCount));
            //处理高亮结果
            HighlightField titleField=hit.getHighlightFields().get("title");
            if (titleField!=null){
                discussPost.setTitle(titleField.getFragments()[0].toString());
            }
            HighlightField contentField=hit.getHighlightFields().get("content");
            if (contentField!=null){
                discussPost.setContent(contentField.getFragments()[0].toString());
            }
            list.add(discussPost);
        }
        Page<DiscussPost> page=new PageImpl<>(list);
        return page;
    }
}
